﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class SystemManage_EmailClient : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["atm"] != null)
            {
                hidAttachment.Value = Server.MapPath("~").ToString() + "/EmailReport/" + Request["atm"].ToString();

                lblAtmFile.Text = hidAttachment.Value.Substring(hidAttachment.Value.LastIndexOf('/')).Replace('/',' ');
            }

            string backUrl = "";
            if (Request["rtn"] != null)
            {
                backUrl = Request["rtn"].ToString();
                if (backUrl == null || backUrl == "" || backUrl == "-1")
                {
                    backUrl = "javascript:history.go(-1);";
                }
            }
            else
            {
                backUrl = "javascript:history.go(-1);";
            }
            lbtnReturn.HRef = backUrl;

            dataBindEmail();
        }
    }

    #region 调出框用到的所有方法
    private void dataBindEmail()
    {
        ViewState["OrderBy"] = "LinkMan";
        ViewState["Accending"] = "desc";
        FillClient();

        ISyClientHandler clientManage = new SyClientHandler();
        string sqlStr = @"SELECT lm.PKID, lm.LinkMan, lm.Email, client.CNShortName as CNClient, client.HKShortName as HKClient, client.ENGShortName as ENGClient
                        FROM Sy_Client client INNER JOIN
                            Sy_ClientLinkMan lm ON client.PKID = lm.ClientID";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = clientManage.GetClientList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvEmailList.DataSource = view;
        gvEmailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }

    }

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        if (ViewState["Value"] != null)
        {
            if (ViewState["Name"].ToString().ToLower() == "linkman")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                sqlstr += " and lm.LinkMan like @ColumnName + '%'";
            }
            else if (ViewState["Name"].ToString().ToLower() == "email")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                sqlstr += " and lm.Email like @ColumnName + '%'";

            }
        }

        if (ViewState["ClientID"] != null)
        {
            list.Add(new SqlParameter("@ClientID", ViewState["ClientID"]));
            sqlstr += " and ClientID = @ClientID";
        }

        parms = list.ToArray();
    }

    private void FillClient()
    {
        ISyClientHandler clientManage = new SyClientHandler();

        ddlClient.DataSource = clientManage.GetClientList("select * from sy_client", new SqlParameter[]{});

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlClient.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlClient.DataTextField = "HKShortName";
        }
        else
        {
            ddlClient.DataTextField = "CNShortName";
        }
        ddlClient.DataValueField = "PKID";
        ddlClient.DataBind();
        ddlClient.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }


    protected void gvEmailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvEmailList.PageIndex = e.NewPageIndex;
        dataBindEmail();
    }

    protected void gvEmailList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblCNClient = (Label)e.Row.FindControl("lblCNClient");
            Label lblHKClient = (Label)e.Row.FindControl("lblHKClient");
            Label lblENGClient = (Label)e.Row.FindControl("lblENGClient");

            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                lblENGClient.Visible = true;
                lblCNClient.Visible = false;
                lblHKClient.Visible = false;

            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                lblENGClient.Visible = false;
                lblCNClient.Visible = false;
                lblHKClient.Visible = true;
            }
            else
            {
                lblENGClient.Visible = false;
                lblCNClient.Visible = true;
                lblHKClient.Visible = false;
            }


        }
    }

    protected void gvEmailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindEmail();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtName.Text != string.Empty)
        {
            ViewState["Value"] = txtName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }

        if (ddlClient.SelectedValue != "0")
        {
            ViewState["ClientID"] = ddlClient.SelectedValue;
        }
        else
        {
            ViewState["ClientID"] = null;
        }
        dataBindEmail();
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvEmailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvEmailList.PageCount)
            {
                this.gvEmailList.PageIndex = i;
                //数据绑定
                dataBindEmail();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvEmailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindEmail();
    }


    protected void btnClose_Click(object sender, EventArgs e)
    {
        CloseSelectRoles();
    }

    protected void btnSub_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            string[] emails = Request["chkSelected"].ToString().Split(',');

            foreach (string newEmail in emails)
            {
                if (newEmail != null && !"".Equals(newEmail) && StringUtil.IsEmailAddress(newEmail))
                {
                    if (!txtMailto.Text.Contains(newEmail))
                    {
                        txtMailto.Text = txtMailto.Text + (!"".Equals(txtMailto.Text.Trim()) && !txtMailto.Text.Trim().EndsWith(";") ? ";" : "") + newEmail + "; ";
                    }
                }
            }
        }
        CloseSelectRoles();
    }

    /// <summary>
    ///
    /// </summary>
    private void CloseSelectRoles()
    {
        myDiv.Style.Add("display", "none");
        divError.Style.Add("display", "none");
    }


    protected void lbtnMailto_Click(object sender, EventArgs e)
    {
        myDiv.Style.Add("display", "block");
        divError.Style.Add("display", "block");
    }
    #endregion

    protected void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            string[] emails = txtMailto.Text.Split(';');
            List<string> mailto = new List<string>();

            foreach (string email in emails)
            {
                if (!"".Equals(email) && StringUtil.IsEmailAddress(email))
                {
                    mailto.Add(email);
                }
            }

            if (mailto.Count > 0)
            {
                string attachment =Server.MapPath("~").ToString() + "/EmailReport/" + Request["atm"];
                SendMail send = new SendMail();
                send.MailBody = txtContents.Value;
                send.MailSubject = txtSubject.Text;

                if (hidAttachment.Value != null && !"".Equals(hidAttachment.Value.Trim()))
                {
                    send.SendAll(mailto.ToArray(), attachment);
                }
                else
                {
                    send.SendAll(mailto.ToArray());
                }
            }

            Jscript.AlertInAjax(Resources.Messages.EmailSent, UpdatePanel1);

            FileTools.DeleteFile("/EmailReport/" + Request["atm"]);
            txtMailto.Text = "";
            txtSubject.Text = "";
            txtContents.Value = "";
        }
        catch (Exception ex)
        {
            Jscript.AlertInAjax(ex.Message, UpdatePanel1);
        }
    }
}
